package com.zr.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zr.model.User;
import com.zr.service.UserService;

public class LoginController extends HttpServlet{
	UserService userService=new UserService();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uname=req.getParameter("uname");
		String upsw=req.getParameter("upsw");
		//当勾选记住我后，记住用户名和密码
		if("on".equals(req.getParameter("remember"))){
			//1.生成cookie对象
			Cookie nameCookie=new Cookie("uname", uname);
			//设置有效期：调用setMaxAge()函数表明cookie在多长时间（以秒为单位）内有效。下面的操作将有效期设为了24小时。
			nameCookie.setMaxAge(60*60*24); 
			Cookie pswCookie=new Cookie("upsw",upsw);
			pswCookie.setMaxAge(60*60*24); 
			//2.将cookie对象添加到本地的客户端
			resp.addCookie(nameCookie);
			resp.addCookie(pswCookie);
		}

		User currentUser=new User(uname,upsw);
		//获取session对象
		HttpSession session=req.getSession();
		boolean flag=userService.validateUser(currentUser);
		if(flag){
			//获取当前用户的对象，放入session中
			session.setAttribute("currentUser",currentUser );
			req.getRequestDispatcher("/workerlist/main.jsp").forward(req, resp);
		}else{
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
		
	}
}
